package com.ex.config;


import com.ex.realm.AuthFilter;
import com.ex.realm.LoginCredentialsMatcher;
import com.ex.realm.LoginRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.Filter;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
public class ShiroConfig {

    /**
     * 配置shiro过滤器信息
     * 1.需要拦截url请求信息
     * 2.拦截失败后返回的url请求信息
     * 3.成功返回的url请求信息
     * 4.
     *
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
        System.out.println("ShiroConfiguration.shirFilter()");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        //未授权界面;
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        /**
         * {@link ShiroUrlMap}
         */
        shiroFilterFactoryBean.setFilterChainDefinitionMap(ShiroUrlMap.filterChainDefinitionMap);

        // 设置shiroFilter，用于拦截权限认证
        Map<String, Filter> map = new ConcurrentHashMap<>();
        map.put("authFilter", authFilter());
        shiroFilterFactoryBean.setFilters(map);

        return shiroFilterFactoryBean;
    }

    @Bean
    public AuthFilter authFilter() {
        return new AuthFilter();
    }

    /**
     * 凭证匹配器
     * （由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
     * ）
     * @return
     */
//    @Bean
//    public HashedCredentialsMatcher hashedCredentialsMatcher(){
//        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
//        hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
//        hashedCredentialsMatcher.setHashIterations(2);//散列的次数，比如散列两次，相当于 md5(md5(""));
//        return hashedCredentialsMatcher;
//    }

    /**
     * 自定义登录凭证管理器
     *
     * @return {@link LoginCredentialsMatcher}
     */
    @Bean
    public LoginCredentialsMatcher loginCredentialsMatcher() {
        return new LoginCredentialsMatcher();
    }

//    @Bean
//    public MyRealm myShiroRealm(){
//        MyRealm myShiroRealm = new MyRealm();
//        myShiroRealm.setCredentialsMatcher(loginCredentialsMatcher());
//        return myShiroRealm;
//    }

    /**
     * 自定义登录realm，交给spring容器管理
     *
     * @return
     */
    @Bean
    public LoginRealm loginRealm() {
        LoginRealm loginRealm = new LoginRealm();

        /*
        realm中缓存处理:
        1.cacheManager
        2.认证缓存
        3.授权缓存
         */
        loginRealm.setCredentialsMatcher(loginCredentialsMatcher());
        return loginRealm;
    }

    /**
     * 安全管理器
     *
     * @return
     */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(loginRealm());
        return securityManager;
    }

//    @Bean
//    public EhCacheManager ehCacheManager(){
//        EhCacheManager ehcacheManager = new EhCacheManager();
//        ehcacheManager.setCacheManagerConfigFile("classpath:ehcache.xml");
//        return ehcacheManager;
//    }


    /**
     * 开启shiro aop注解支持.
     * 使用代理方式;所以需要开启代码支持;
     *
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    @Bean(name = "simpleMappingExceptionResolver")
    public SimpleMappingExceptionResolver
    createSimpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
        Properties mappings = new Properties();
        mappings.setProperty("DatabaseException", "databaseError");//数据库异常处理
        mappings.setProperty("UnauthorizedException", "403");
        r.setExceptionMappings(mappings);  // None by default
        r.setDefaultErrorView("error");    // No default
        r.setExceptionAttribute("ex");     // Default is "exception"
        //r.setWarnLogCategory("ex.MvcLogger");     // No default
        return r;
    }
}